<template>
  <div class="page-wrapper">
    <el-container>
      <el-aside class="left" width="200px">
        <el-scrollbar>
          <div
            class="user-item"
            :class="selectUserId === item.id ? 'on' : ''"
            @click="onClickUser(item.id || 0)"
            v-for="(item, i) in allUser"
            :key="i"
          >
            <el-avatar :size="50" src="" />
            <div class="user-item-right">
              <div>{{ item.name }}</div>
              <div style="font-size: var(--el-font-size-extra-small)">
                {{ item.userType }}
              </div>
            </div>
          </div>
        </el-scrollbar>
      </el-aside>
      <el-main class="right-wrapper">
        <el-tabs type="border-card">
          <el-tab-pane label="目录权限" style="height: 100%">
            <el-scrollbar style="width: 100%; height: calc(100% - 32px)">
              <el-tree
                ref="treeRef"
                class="dir-tree"
                node-key="path"
                lazy
                :data="dirTree"
                :load="loadNode"
                :check-strictly="false"
                :props="{
                  children: 'children',
                  label: 'path',
                }"
                show-checkbox
              >
                <template #default="{ node, data }">
                  <div class="disk-item" :class="data.root ? 'root' : ''">
                    <div class="disk-title-wrapper">
                      <img
                        v-if="data.root"
                        :class="`disk-icon disk-icon-${data.driveType}`"
                        src=""
                        alt=""
                      />
                      <span>{{ node.label }}</span>
                      <span class="title">
                        {{ data.label }}
                      </span>
                    </div>
                  </div>
                </template>
              </el-tree>
            </el-scrollbar>
            <div>
              <el-button @click="handleSavePath">保存目录</el-button>
            </div>
          </el-tab-pane>
          <el-tab-pane label="修改密码">
            <el-form
              :model="formData"
              ref="vForm"
              :rules="rules"
              label-position="left"
              label-width="80px"
              size="medium"
              @submit.prevent
            >
              <el-form-item label="新密码" prop="password" class="required">
                <el-input
                  v-model="formData.password"
                  type="text"
                  placeholder="请输入新密码"
                  clearable
                ></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitForm(vForm)">提交</el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="Role">Role</el-tab-pane>
          <el-tab-pane label="Task">Task</el-tab-pane>
        </el-tabs>
      </el-main>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import sysUserService from "@/api-services/apis/sysUser";
import nasFileService from "@/api-services/apis/nasFile";
import bus from "vue3-eventbus";
import { GetAllDiskResult, SysUser } from "@/api-services/models";
import { Tree, TreeNode } from "element-plus/es/components/tree-v2/src/types";
import { ElNotification, FormInstance, ElMessage } from "element-plus";

const treeRef = ref<any>(null);
const allUser = ref<SysUser[]>([]);
const selectUserId = ref<number>(-1);
const diskList = ref<GetAllDiskResult[]>([]);
const dirTree = ref<GetAllDiskResult[]>([]);
const vForm = ref<FormInstance>();
const formData = ref({
  password: "",
});

const rules = ref({
  password: [
    {
      required: true,
      message: "字段值不可为空",
    },
  ],
});

bus.on("add_account", () => {
  console.log("add_account");
});
bus.on("modify_password", () => {
  console.log("modify_password");
});
bus.on("folder_permission", () => {
  console.log("folder_permission");
});
bus.on("del_account", () => {
  console.log("del_account");
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      await sysUserService.ModifyPassword(formData.value.password);
      ElMessage({
        type: "success",
        message: "密码修改成功",
      });
      console.log("submit!");
    } else {
      console.log("error submit!", fields);
    }
  });
};

async function handleAllUser() {
  allUser.value = await sysUserService.AllUser();
}
handleAllUser();

const loadNode = async (node: TreeNode, resolve: (data: Tree[]) => void) => {
  if (node.level === 0) {
    let data = await nasFileService.GetAllDisk();
    return resolve(data as any);
  } else {
    let path = node.data.path;
    console.log(node.data);
    path = path ? `${path}${/\\$/.test(path) ? "" : "\\"}` : path;
    let data = (await nasFileService.GetFolderTree({
      path: path || diskList.value![0].path,
    })) as any;
    if (allKeys.filter((x) => x == node.data.path).length > 0) {
      //当前节点是选中状态  则子级也全部选中
      let paths = data.map((x) => x.path);
      allKeys = allKeys.concat(paths);
      console.log(allKeys);

      treeRef.value.setCheckedKeys(allKeys);
    }
    return resolve(data);
  }
};

let allKeys = <string[]>[];
async function onClickUser(userId: number) {
  selectUserId.value = userId;
  let nodes = await sysUserService.GetFolderByUser(userId);
  // 加载所有选中的
  let keys = nodes.filter((x) => !x.half).map((x) => x.path);
  console.log(keys);
  allKeys = keys;
  treeRef.value.setCheckedKeys(keys);
}

async function handleSavePath() {
  if (!(selectUserId.value > 0)) {
    ElNotification({
      title: "错误",
      message: "请先选择用户",
      type: "error",
    });
    return;
  }
  let nodes = treeRef.value!.getCheckedKeys().map((x) => {
    return {
      path: x,
      half: false,
    };
  });
  let halfNodes = treeRef.value!.getHalfCheckedKeys().map((x) => {
    return {
      path: x,
      half: true,
    };
  });
  console.log(halfNodes, nodes);
  await sysUserService.SetUserFolder({
    userId: selectUserId.value,
    folders: nodes.concat(halfNodes),
  });
}
</script>

<style lang="scss" scoped>
.page-wrapper {
  display: flex;
  height: 100%;
  // min-height: 400px;
  width: 100%;
  color: #333;
  text-shadow: none;
  font-weight: 300;
  overflow: hidden;
  .left {
    background: rgba(255, 255, 255, 0.8);
    backdrop-filter: blur(20px);
    display: flex;
    flex-direction: row;
    // justify-content: center;
    // align-items: center;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }
  .user-item {
    display: flex;
    padding: 5px 10px;
    cursor: pointer;
    .user-item-right {
      flex: 1;
      padding-left: 10px;
      div {
        height: 25px;
        line-height: 25px;
      }
    }
  }
  .user-item.on {
    background: rgb(0 0 0 / 4%);
  }

  .right-wrapper {
    padding: 0;
    .el-tabs {
      display: flex;
      flex-direction: column;
      height: 100%;
      box-sizing: border-box;
      ::v-deep(.el-tabs__content) {
        height: 100%;
        flex: 1;
      }
    }
  }
}
</style>
